package com.road.filter;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.road.model.Msg;
import com.road.model.User;
import com.road.service.IUserService;
import com.road.service.imp.UserServiceImp;
import com.road.utils.Consists;
import com.road.utils.ResponseUtil;

/**
 * Servlet Filter implementation class TokenAuther
 */
//@WebFilter(description = "token权限过滤", urlPatterns = { "/*" }, 
//initParams={@WebInitParam(name ="chain_do" , value = "login;register;upload")})
public class TokenAuther implements Filter {
	Logger log=Logger.getLogger(TokenAuther.class.getName());
	IUserService  us=new UserServiceImp();
	private String chain_do_str;       
	private String[] chain_do_arr;
    /**
    /**
     * Default constructor. 
     */
    public TokenAuther() {
        // TODO Auto-generated constructor stub
    	log.info("************TokenAuther************");
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
		log.info("************destroy************");
	       this.chain_do_str = null; 
	       this.chain_do_arr = null; 
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		  HttpServletRequest req=(HttpServletRequest)request;
		  String url=req.getServletPath();
		  boolean needFilter = true;  
	        for (String page : chain_do_arr) {// 遍历例外url数组   
	            // 判断当前URL是否与例外页面相同 
	            if(url.substring(1).equals(page)){ // 从第2个字符开始取（把前面的/去掉） 
	                needFilter = false;     
	                break;     
	            }     
	        }   
	        if (!needFilter) {//在过滤url之外     
	            chain.doFilter(request, response);     
	        } else {// 不在过滤url之外
	        	//访问数据接口
				String token=request.getParameter("token");
				boolean isok = us.cheakToken(new User(token));
				//验证成功继续执行
				if (isok) {
					chain.doFilter(request, response);
				}else {
				   //提示验证失败
					Msg msg=new Msg();
					msg.setCode(Consists.Error_Code_TokenTimeout);
					msg.setMsg(Consists.Error_Msg__TokenTimeout);
					ResponseUtil.sendScript((HttpServletResponse)response, JSON.toJSONString(msg));
				}
	        }
		
		
		// pass the request along the filter chain
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		 log.info("************FilterConfiginit************");
		 chain_do_str = fConfig.getInitParameter("chain_do");     
	        if (null!=chain_do_str && chain_do_str.length()!=0) { // 不需要过滤的方法
	            chain_do_arr = chain_do_str.split(String.valueOf(';'));     
	        }    
	}

}
